package com.sitia.jd.service.impl;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sitia.common.CustomException;
import com.sitia.common.utils.DateUtils;
import com.sitia.common.utils.SecurityUtils;
import com.sitia.common.utils.StringUtils;
import com.sitia.common.utils.poi.ExcelUtil;
import com.sitia.common.utils.uuid.IdUtils;
import com.sitia.jd.domain.MxOrder;
import com.sitia.jd.domain.dto.ImportRebateOrderVo;
import com.sitia.jd.domain.dto.keyValueBo;
import com.sitia.jd.domain.vo.RebateChartVo;
import com.sitia.jd.domain.vo.RebateOrderStatisticsVo;
import com.sitia.jd.domain.vo.RebateStatisticsVo;
import com.sitia.jd.enums.MxRebateOrderEnum;
import com.sitia.jd.mapper.MxOrderMapper;
import com.sitia.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sitia.jd.mapper.MxRebateOrderMapper;
import com.sitia.jd.domain.MxRebateOrder;
import com.sitia.jd.service.IMxRebateOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 返利订单Service业务层处理
 * 
 * @author sitia
 * @date 2024-03-08
 */
@Service
@Slf4j
public class MxRebateOrderServiceImpl extends ServiceImpl<MxRebateOrderMapper,MxRebateOrder>  implements IMxRebateOrderService
{
    @Autowired
    private MxRebateOrderMapper mxRebateOrderMapper;
    @Autowired
    private MxOrderMapper mxOrderMapper;

    @Autowired
    private IMxRebateOrderService mxRebateOrderService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询返利订单
     * 
     * @param id 返利订单主键
     * @return 返利订单
     */
    @Override
    public MxRebateOrder selectMxRebateOrderById(String id)
    {
        return mxRebateOrderMapper.selectMxRebateOrderById(id);
    }

    /**
     * 查询返利订单列表
     * 
     * @param mxRebateOrder 返利订单
     * @return 返利订单
     */
    @Override
    public List<MxRebateOrder> selectMxRebateOrderList(MxRebateOrder mxRebateOrder)
    {
        if (mxRebateOrder.getPresetTimes() != null) {
            mxRebateOrder.setPresetTimeStar(mxRebateOrder.getPresetTimes()[0]);
            mxRebateOrder.setPresetTimeEnd(mxRebateOrder.getPresetTimes()[1]);
        }
        return mxRebateOrderMapper.selectMxRebateOrderList(mxRebateOrder);
    }

    /**
     * 查询网页
     * @param mxRebateOrder
     * @return
     */
    @Override
    public List<MxRebateOrder> pageList(MxRebateOrder mxRebateOrder) {
        if (mxRebateOrder.getPresetTimes() != null) {
            mxRebateOrder.setPresetTimeStar(mxRebateOrder.getPresetTimes()[0]);
            mxRebateOrder.setPresetTimeEnd(mxRebateOrder.getPresetTimes()[1]);
        }
        mxRebateOrder.setIsRebate(MxRebateOrderEnum.REBATE);
        return mxRebateOrderMapper.selectMxRebateOrderList(mxRebateOrder);
    }

    @Override
    public List<RebateStatisticsVo> queryRebatePie(MxRebateOrder mxRebateOrder) {
        if (mxRebateOrder.getPresetTimes() != null) {
            mxRebateOrder.setPresetTimeStar(mxRebateOrder.getPresetTimes()[0]);
            mxRebateOrder.setPresetTimeEnd(mxRebateOrder.getPresetTimes()[1]);
        }
        List<RebateStatisticsVo> rebateStatisticsVos = mxRebateOrderMapper.queryRebatePieDate(mxRebateOrder);

        return rebateStatisticsVos;
    }

    @Override
    public RebateOrderStatisticsVo rebateStatistics(MxRebateOrder mxRebateOrder) {
        if (mxRebateOrder.getPresetTimes() != null) {
            mxRebateOrder.setPresetTimeStar(mxRebateOrder.getPresetTimes()[0]);
            mxRebateOrder.setPresetTimeEnd(mxRebateOrder.getPresetTimes()[1]);
        }
        RebateOrderStatisticsVo successStatistics = mxRebateOrderMapper.rebateSuccessStatistics(mxRebateOrder);
        RebateOrderStatisticsVo allRebate = mxRebateOrderMapper.queryAllRebateStatistics(mxRebateOrder);
        allRebate.setFinishPrice(successStatistics.getFinishPrice());
        allRebate.setFinishCount(successStatistics.getFinishCount());
        return allRebate;
    }

    /**
     * 返利统计
     * @param mxRebateOrder
     * @return
     */
    @Override
    public RebateChartVo rebateChart(MxRebateOrder mxRebateOrder) {
        if (mxRebateOrder.getPresetTimes() != null) {
            mxRebateOrder.setPresetTimeStar(mxRebateOrder.getPresetTimes()[0]);
            mxRebateOrder.setPresetTimeEnd(mxRebateOrder.getPresetTimes()[1]);
        }
        RebateChartVo rebateChartVo = new RebateChartVo();
        List<keyValueBo> keyValueBos = mxRebateOrderMapper.selectRebateChar(mxRebateOrder);
        if (keyValueBos.size() >0) {
            ArrayList<String> labels = new ArrayList<>();
            ArrayList<String> values = new ArrayList<>();
            keyValueBos.forEach(bo->{
                labels.add(bo.getKey());
                values.add(bo.getValue());
            });
            rebateChartVo.setLabels(labels).setValues(values);
        }

        return rebateChartVo;
    }

    /**
     * 新增返利订单
     * 
     * @param mxRebateOrder 返利订单
     * @return 结果
     */
    @Override
    public int insertMxRebateOrder(MxRebateOrder mxRebateOrder)
    {
        mxRebateOrder.setId(IdUtils.simpleUUID()).setCreateTime(DateUtils.getNowDate());
        return mxRebateOrderMapper.insertMxRebateOrder(mxRebateOrder);
    }

    /**
     * 修改返利订单
     * 
     * @param mxRebateOrder 返利订单
     * @return 结果
     */
    @Override
    public int updateMxRebateOrder(MxRebateOrder mxRebateOrder)
    {
        mxRebateOrder.setUpdateTime(DateUtils.getNowDate());
        return mxRebateOrderMapper.updateMxRebateOrder(mxRebateOrder);
    }

    /**
     * 批量删除返利订单
     * 
     * @param ids 需要删除的返利订单主键
     * @return 结果
     */
    @Override
    public int deleteMxRebateOrderByIds(String[] ids)
    {
        return mxRebateOrderMapper.deleteMxRebateOrderByIds(ids);
    }

    /**
     * 删除返利订单信息
     * 
     * @param id 返利订单主键
     * @return 结果
     */
    @Override
    public int deleteMxRebateOrderById(String id)
    {
        return mxRebateOrderMapper.deleteMxRebateOrderById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int importIdAndOrderExcel(List<MultipartFile> fileList, String date) {
        int successInsert = 0;
        for (MultipartFile file : fileList) {
            ExcelUtil<ImportRebateOrderVo> util = new ExcelUtil<>(ImportRebateOrderVo.class);

            try {
                List<ImportRebateOrderVo> importRebateOrderVos = util.importExcel(file.getInputStream());
                if (CollectionUtil.isEmpty(importRebateOrderVos)) {
                    throw new CustomException("未获取到表格数据");
                }
                // 判读数据库中是否存在该订单且返利表中不存在，存在添加订单，返利表中存在则更新
                for (ImportRebateOrderVo importRebateOrderVo : importRebateOrderVos) {
                    String mxOrderID = importRebateOrderVo.getId();
                    String jdOrders = importRebateOrderVo.getOrder();
                    if (StringUtils.isEmpty(mxOrderID)||StringUtils.isEmpty(jdOrders)) {
                        continue;
                    }
                    MxOrder mxOrder = mxOrderMapper.selectMxOrderById(mxOrderID);
                    if (ObjectUtil.isEmpty(mxOrder)) {
                        continue;
                    }
                    List<MxRebateOrder> mxRebateOrders = mxRebateOrderMapper.selectMxRebateOrderList(new MxRebateOrder().setMxOrderId(mxOrderID));
                    if (mxRebateOrders.size() > 0) {
                        //修改
                        mxRebateOrders.forEach(mxRebateOrder -> mxRebateOrder.setJdOrders(jdOrders).setUpdateTime(DateUtils.getNowDate()));
                        this.updateBatchById(mxRebateOrders);
                    } else {
                        //添加
                        Date now = DateUtils.getNowDate();
                        MxRebateOrder mxRebateOrder = new MxRebateOrder()
                                .setCreateBy(SecurityUtils.getUserId().toString())
                                .setMxOrderId(mxOrderID)
                                .setJdOrders(jdOrders)
                                .setIsRebate(MxRebateOrderEnum.NO_REBATE)
                                .setOwnerUserId(mxOrder.getOwnerUserId().toString())
                                .setOwnerUserName(mxOrder.getOwnerUserName())
                                .setPresetTime(mxOrder.getPresetTime());
                        successInsert += this.insertMxRebateOrder(mxRebateOrder);
                    }

                }
            } catch (Exception e) {
                log.error("处理Excel失败",e);
                throw new CustomException("处理Excel失败，具体原因："+ e.getMessage());
            }
        }

        return successInsert;
    }

    @Override
    public int importJinFenCsv(MultipartFile file, MxRebateOrder mxRebateOrder) {
        String jingfenBy = mxRebateOrder.getJingfenBy();
        String jingfengBy = StringUtils.isNotEmpty(jingfenBy) ? jingfenBy : SecurityUtils.getUserId().toString();
        String userName = userService.selectUserById(Long.parseLong(jingfengBy)).getUserName();
        String property = System.getProperty("user.dir");
        String excelPath = property + File.separator + file.getOriginalFilename().replace(".csv", ".xlsx");
        String s = convertCsvToExcel(file, excelPath);
        ExcelUtil<MxRebateOrder> util = new ExcelUtil<>(MxRebateOrder.class);
        File excel = new File(s);
        int success = 0;
        try {
            List<MxRebateOrder> mxRebateOrders = util.importExcel(Files.newInputStream(excel.toPath()));
            if (CollectionUtil.isEmpty(mxRebateOrders)) {
                throw new CustomException("未获取到表格数据");
            }
            Date now = DateUtils.getNowDate();
            for (MxRebateOrder mxOrder : mxRebateOrders) {
                String orderId = mxOrder.getOrderId();
                if (StringUtils.isEmpty(orderId)) {
                    continue;
                }
                //根据订单号查询出返利信息
                List<MxRebateOrder> rebates = mxRebateOrderMapper.selectMxRebateOrderList(new MxRebateOrder()
                        .setJdOrders(orderId));
                if (CollectionUtil.isEmpty(rebates)) {
                    continue;
                }
                //不为空，更新信息
                for (MxRebateOrder rebate : rebates) {
                    mxOrder.setId(rebate.getId())
                            .setIsRebate(MxRebateOrderEnum.REBATE)
                            .setUpdateTime(now)
                            .setJingfenBy(jingfengBy)
                            .setJingfenName(userName);
                    success += mxRebateOrderMapper.updateMxRebateOrder(mxOrder);
                }
            }

        } catch (Exception e) {
            log.error("解析excel失败",e);
            throw new CustomException("解析excel失败，具体原因：" + e.getMessage());
        } finally {
            FileUtil.del(excel);
        }
        //log.info("成功更新："+success);
        return success;
    }



    /**
     * 蒋csv文件转换为excel
     * @param file csv文件
     * @param excelFilePath  转换文件的地址
     * @return excel文件路径
     */
    private String convertCsvToExcel(MultipartFile file, String excelFilePath) {
        //String excelFilePath = "path/to/temp/output.xlsx";

        try (InputStream inputStream = file.getInputStream()) {
            // 创建一个新的工作簿
            Workbook workbook = new XSSFWorkbook();
            workbook.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            Sheet sheet = workbook.createSheet("京粉数据");

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"))) {
                String line;
                int rowNum = 0;
                while ((line = reader.readLine()) != null) {
                    Row row = sheet.createRow(rowNum++);
                    String[] values = line.split(",");

                    for (int i = 0; i < values.length; i++) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(new XSSFRichTextString(values[i]));
                    }
                }
            }

            try (FileOutputStream output = new FileOutputStream(excelFilePath)) {
                workbook.write(output);
            }
        } catch (IOException e) {
            log.error("csv文件转换成excel失败", e);
            throw new CustomException("csv文件转换成excel失败");
        }

        return excelFilePath;
    }
}
